package amalgame.ventas;

import java.util.Date;
import java.util.List;

import amalgame.data.DatabaseManager;
import amalgame.entity.Actividad;
import amalgame.entity.Util;
import amalgame.entity.db.Customer;
import amalgame.entity.db.OrderProduct;
import amalgame.entity.db.Product;
import amalgame.entity.db.Stock;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class AddOrderProductActivity extends Actividad {
	private Button btn_cancel;
	private Button btn_save;
	private Dialog dialog_confirmation;
	private Util utilman;
	private DatabaseManager manager;
	private Context mContext;
	
	private Product product_selection;
	private Spinner sp_Product;
	private EditText txt_quantity;
	private TextView tv_quantity;
	
	private ArrayAdapter<String> arrAdapter_productos ;
	private List<Product> list_products;
	private String pathphoto = "";
	private int order_selection=0;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_order_product);
               
		sp_Product = (Spinner) findViewById(R.id.addorder_product_order_spinner_productId);
		txt_quantity = (EditText) findViewById(R.id.addorder_product_order_edittext_quantity);
		tv_quantity = (TextView) findViewById(R.id.addorder_product_order_textView_quantityAvailable);
		
		
		mContext = getApplicationContext();
		utilman = Util.getInstanceUtil();
		manager = DatabaseManager.getInstance();
		
		
		
		Bundle bundle = getIntent().getExtras();
		if(bundle!=null){
			order_selection= bundle.getInt("ORDER-ID");
			System.out.println( " ORDER ID :"+ getString(R.string.order_n_) + " " + order_selection );			
		}
		
		
		
		int quantityAvailable = manager.getQuantityByProductId(order_selection) ;
		tv_quantity.setText(getResources().getString(R.string.quantity_available_)+ " " + String.valueOf(quantityAvailable));
		
		
		
		String[] arrProductos = null;		
		list_products= manager.getAllproduct();
		
		arrProductos = new String[list_products.size()];
		int i=0;
		for (Product item : list_products) {
			arrProductos[i] =item.getName();
			i++;
		}
		if(arrProductos!=null){
			arrAdapter_productos = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,arrProductos);
			sp_Product.setAdapter(arrAdapter_productos);
		}
		
		
		btn_cancel =  (Button)findViewById(R.id.addorder_product_button_cancel);
		btn_cancel.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
	
		btn_save = (Button)findViewById(R.id.addorder_product_button_save);
		btn_save.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {			
				validate();
			}
		});
		
	
		
		sp_Product.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parentView,View selectedItemView, int position, long id) {
					try {
						String str_customer = sp_Product.getSelectedItem().toString();
						
						//List<Customer> listCustomer = manager.getAllCustomer();
						
						int i = 0;
						int iditem = -1;
						for (Product item :  list_products) {
							if (item.getName().equals(str_customer)) {
								iditem = item.getProductId();
								break;
							}
					
							i++;
						}
						if(iditem!=-1)
						{
							
							product_selection = manager.getProductByID(iditem);
							int quantityAvailable = manager.getQuantityByProductId(iditem) ;
							tv_quantity.setText(getResources().getString(R.string.quantity_available_)+ " " + String.valueOf(quantityAvailable));
							
						}
						
					
						
					} catch (Exception e) {
						e.printStackTrace();
					}
				

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}

		});
    }


	private void validate(){
		
		
		if (txt_quantity.getText().toString().equals("") ) {
			dialog_confirmation = utilman
					.showDialog(
							getString(R.string.complete_all_required_fields_before_continue),
							getString(R.string.atention),
							AddOrderProductActivity.this
							);
			try {
				dialog_confirmation.show();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		else{
			
		
			
			int int_quantity= Integer.parseInt(txt_quantity.getText().toString());
			//int int_productCantity=  manager.getProductByID(product_selection.getProductId()).getQuantity();
			int int_productquantity=  manager.getQuantityByProductId(product_selection.getProductId());
			if(int_quantity==0){
				return;
			}
			if ( int_quantity <= int_productquantity) {
				
				
			
				
				String description =  txt_quantity.getText().toString();
				
		
				//adding the event to log stock
				Stock stock =new Stock(new Date().toString() ,product_selection.getProductId(), int_quantity * -1);
				manager.addStock(stock);
				
				//update the new Product QUANTITY! 
				int_productquantity=  manager.getQuantityByProductId(product_selection.getProductId());
				product_selection.setQuantity(int_productquantity);
				boolean ret = manager.updateProduct(product_selection);
				
				
				if (ret) {

					OrderProduct p ;
					p  = new OrderProduct(order_selection ,product_selection.getProductId(), int_quantity);			
					manager.addOrderProduct(p);
					Toast.makeText(mContext, "The new item is added", Toast.LENGTH_LONG).show();
					
					
				} else {
					Toast.makeText(mContext,
							getString(R.string.failed_to_update_the_item),
							Toast.LENGTH_LONG).show();

				}
				
			
				
				
				
				finish();
			
			}else {
				Toast.makeText(mContext,
						getString(R.string.no_stock_sufficient),
						Toast.LENGTH_LONG).show();

			}
		}
		
		
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		//return super.onCreateOptionsMenu(menu);
		
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.add_product_order , menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem menu) {
		// TODO Auto-generated method stub
		//return super.onOptionsItemSelected(menu);
		
		if(menu.getItemId()==R.id.menu_addproduct_order_categorie){
			Intent intent = new Intent();
			intent.setClass(mContext, CategoriesActivity.class);
			startActivity(intent);
			
			
			return true;
		}
		
		return false;
	}
    
}
